﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 记事本
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void toolStripMenuItem3_Click(object sender, EventArgs e)
        {
            SaveFile();
        }

        private void toolStripMenuItem4_Click(object sender, EventArgs e)
        {
            Close();
        }

        /// <summary>
        /// 关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void SaveFile()
        {
            SaveFileDialog file = new SaveFileDialog();//定义新的文件保存位置控件
            file.Filter = "txt文件(*.txt)|*.txt";//设置文件后缀的过滤
            if (file.ShowDialog() == DialogResult.OK)//如果有文件保存路径
            {
                StreamWriter sw = File.CreateText(file.FileName);

                sw.Write(uiRichTextBox1.Text);  //写入文件中
                sw.Flush();//清理缓冲区
                sw.Close();//关闭文件
            }
        }

        /// <summary>
        /// 保存文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            SaveFile();
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            uiRichTextBox1.Text = "";
        }


        /// <summary>
        /// 打开文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            OpenFile();
        }

        private void OpenFile()
        {
            OpenFileDialog file = new OpenFileDialog();//定义新的文件打开位置控件
            file.Filter = "txt文件(*.txt)|*.txt";//设置文件后缀的过滤
            if (file.ShowDialog() == DialogResult.OK)//如果有选择打开文件
            {
                FileStream fs = new FileStream(file.FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                StreamReader sr = new StreamReader(fs, System.Text.Encoding.UTF8);   //选择编码方式               
                uiRichTextBox1.Text = "";
                while (sr.EndOfStream != true)
                {
                    string str = sr.ReadLine();
                    uiRichTextBox1.AppendText(str);
                }
            }
        }

        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            uiRichTextBox1.Text = "";
        }
    }
}
